<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>home</title>
    <link rel="stylesheet" href="/static/font/css/material-design-iconic-font.min.css" type="text/css">
    <link rel="stylesheet" href="/static/css/bootstrap-datepicker.min.css" type="text/css">
    <link rel="stylesheet" href="/static/css/style.min.css" type='text/css'>
    <script src="/static/js/jquery-3.2.0.min.js"></script>
    <style>
        .alert {
            padding: 15px 20px;
            background-color: #4CAF50;
            color: white;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            position: absolute;
            top: 50%;
            left: -30%;
            /* 起始位置在左侧屏幕外 */
            transform: translateY(-50%);
            z-index: 9999;
            opacity: 0;
            /* 初始时隐藏 */
            animation: fadeInCenterOut 3s ease forwards;
            /* 使用动画效果 */
            display: none;
        }

        @keyframes fadeInCenterOut {
            0% {
                opacity: 0;
                left: -30%;
                /* 起始位置在左侧屏幕外 */
            }

            10% {
                opacity: 1;
                left: 50%;
                /* 移动到屏幕中央位置 */
            }

            90% {
                opacity: 1;
                left: 50%;
                /* 停留在屏幕中央位置 */
            }

            100% {
                opacity: 0;
                left: 50%;
                /* 仍然停留在屏幕中央位置 */
            }
        }
    </style>
</head>

<body>
    <div id="layout" class="theme-cyan">
        <!-- 左侧导航条 -->
        <div class="navigation navbar justify-content-center py-xl-4 py-md-3 py-0 px-3">
            <div class="nav flex-md-column nav-pills flex-grow-1" role="tablist" aria-orientation="vertical">
                <a class="mb-xl-3 mb-md-2 nav-link" data-toggle="pill" href="/index/" role="tab">
                    <img src="/static/images/user1.jpg" class="avatar sm rounded-circle" alt="user avatar" />
                </a>
                <a class="mb-xl-3 mb-md-2 nav-link" type="button" id="joinclick">
                    <i class="zmdi zmdi-plus"></i>
                </a>
                <a class="mt-xl-3 mt-md-2 nav-link" type="button" id="createclick">
                    <i class="zmdi zmdi-account-add"></i>
                </a>
            </div>
            <button type="submit" class="btn sidebar-toggle-btn shadow-sm"><i class="zmdi zmdi-menu"></i></button>
        </div>


        <!-- 消息列表 -->
        <div class="sidebar border-end py-xl-4 py-3 px-xl-4 px-3"
            style="background-image: url('/static/images/background.jpg')">
            <div class="tab-content">
                <div class="tab-pane fade show active" id="indexpage" role="tabpanel">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3 class="mb-0 text-primary">消息列表</h3>
                        <div>
                            <a class="btn btn-dark" type="button" onclick="leave();">退出</a>
                        </div>
                    </div>
                    <ul class="chat-list">
                        {% for gid in gid_list %}
                        <li>
                            <a class="card" type="button" onclick="selectchat(this);" gid={{ gid }}>
                                <div class="card-body">
                                    <div class="media">
                                        <div class="avatar me-3">
                                            <span class="status rounded-circle"></span>
                                            <img class="avatar rounded-circle" src="/static/images/user3.jpg"
                                                alt="avatar">
                                        </div>
                                        <div class="media-body overflow-hidden">
                                            <div class="d-flex align-items-center mb-1">
                                                <h6 class="text-truncate mb-0 me-auto">{{ gid }}</h6>
                                                <p class="small text-muted text-nowrap ms-4 mb-0">聊天室</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
                <div class="tab-pane fade" id="joinpage" role="tabpanel">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3 class="mb-0 text-primary">房间号</h3>
                        <div>
                            <input type="text" class="form-control form-control-lg" id="jointxt" placeholder="加入房间号...">
                        </div>
                        <div>
                            <a class="btn btn-dark" type="button" id="joingroup">加入</a>
                        </div>
                    </div>
                </div>
                <div class="tab-pane fade" id="createpage" role="tabpanel">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3 class="mb-0 text-primary">房间号</h3>
                        <div>
                            <input type="text" class="form-control form-control-lg" id="gidtxt" placeholder="创建房间...">
                        </div>
                        <div>
                            <a class="btn btn-dark" type="button" id="creategroup">创建</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧聊天界面内容 -->
        <div class="main px-xl-5 px-lg-4 px-3" style="display: none">
            <div class="chat-body" style="background-image: url('/static/images/background.jpg')">
                <div class="chat-header border-bottom py-xl-4 py-md-3 py-2">
                    <div class="container-xxl">
                        <div class="row align-items-center">
                            <div class="col-6">
                                <div class="media">
                                    <div class="me-3 show-user-detail">
                                        <span class="status rounded-circle"></span>
                                        <img class="avatar rounded-circle" src="/static/images/user3.jpg" alt="avatar">
                                    </div>
                                    <div class="media-body overflow-hidden">
                                        <div class="d-flex align-items-center mb-1">
                                            <h6 class="text-truncate mb-0 me-auto" id="roomid"></h6>
                                        </div>
                                        <div id="online-user">群聊在线人数：<span>ddd</span></div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6" style="text-align: right">
                                <a class="btn btn-dark" type="button" onclick="closeConn();">退出聊天室</a>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="chat-content">
                    <div class="container-xxl">
                        <ul class="list-unstyled py-4" id="chatbox">
                            <!-- 对话内容 -->
                        </ul>
                    </div>
                </div>

                <div class="chat-footer border-top py-xl-4 py-lg-2 py-2">
                    <div class="container-xxl">
                        <div class="row">
                            <div class="col-12">
                                <div class="input-group align-items-center">
                                    <input type="text" class="form-control border-0 pl-0" id="inputtxt"
                                        placeholder="输入信息...">
                                    <div class="input-group-append">
                                        <span class="input-group-text border-0 pr-0">
                                            <button type="button" class="btn btn-primary" id="sendmsg"
                                                onclick="sendMessage();" uid={{ uid }}>
                                                <span class="d-none d-md-inline-block me-2">发送</span>
                                                <i class="zmdi zmdi-mail-send"></i>
                                            </button>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="alert" class="alert"></div>
    <script>
        // 用户名uid 和 房间号gid 可以唯一确定一个websocket连接
        var wsdir = {};// socket对象存储
        var ws = {};
        var allws = {};

        // 获取当前用户加入的所有群聊（websocket）
        $(function () {
            console.log("初始化1！");
            $.ajax({
                url: "/get/websocket/",
                type: "get",
                data: {},
                dataType: "JSON",
                success: function (request) {
                    if (request.status) {
                        ws = JSON.parse(request.queryset);
                        console.log(ws);
                        for (var i = 0; i < ws.length; i++) {
                            wsdir[ws[i].fields.uid + ws[i].fields.gid] = buildWebsocket(ws[i].fields.uid, ws[i].fields.gid);
                        }
                    }
                }
            });
        })

        // 获取所有的websocket连接对象
        $(getallws());
        function getallws() {
            console.log("初始化2！");
            $.ajax({
                url: "/get/allwebsocket/",
                type: "get",
                data: {},
                dataType: "JSON",
                success: function (request) {
                    if (request.status) {
                        allws = JSON.parse(request.allws);
                    }
                }
            });
        }

        // 加入房间的界面
        $('#joinclick').click(function () {
            $('.tab-pane').removeClass('active show');
            $('#joinpage').addClass('active show');
            getallws();
        });

        // 创建房间的界面
        $('#createclick').click(function () {
            $('.tab-pane').removeClass('active show');
            $('#createpage').addClass('active show');
            getallws();
        });

        // 点击加入聊天室按钮，建立websocket连接，判断房间号存不存在，采用localStrage判断是否存不存在
        $('#joingroup').click(function () {
            var gid = $('#jointxt').val();
            var flag = false;
            // flag用来标记,localStorage中是否有等与tag的房间号
            for (let i = 0; i < allws.length; i++) {
                if (allws[i].fields.gid == gid) {
                    flag = true;
                    break;
                }
            }
            // 如果输入房间号为空
            if (gid === "") alert("输入房间号为空！");
            else if (!flag) {
                // 如果不存在
                alert("输入的房间号不存在！");
            } else {
                // 建立websocket连接，uid和gid唯一确定一个websocket连接
                var uid = $('#sendmsg').attr('uid');
                // 存在该websocket，也就是已经加入了这个群聊
                if (wsdir[uid + gid] != null) {
                    alert('你已经加入这个群聊！')
                } else {
                    wsdir[uid + gid] = buildWebsocket(uid, gid);
                    addwebsocket(uid, gid);
                }
            }
            window.location.href = '/index/'
            window.location.reload()
        });

        // 点击创建聊天室按钮，建立websocket连接
        $('#creategroup').click(function () {
            var gid = $('#gidtxt').val();
            var uid = $('#sendmsg').attr('uid');
            var flag = false;

            // flag用来标记,是否有等与tag的房间号
            for (let i = 0; i < allws.length; i++) {
                if (allws[i].fields.gid == gid) {
                    flag = true;
                    break;
                }
            }
            // 如果输入房间号为空
            if (gid == "") alert("输入房间号为空！");
            // 房号存在 且 当前用户已加入群聊
            if (flag && wsdir[uid + gid] != null) {
                alert('你已经加入这个群聊！');
            }
            // 房号存在
            else if (flag) {
                alert("输入的房间号已存在！");
            } else {
                // 建立websocket连接，uid和gid唯一确定一个websocket连接
                wsdir[uid + gid] = buildWebsocket(uid, gid);
                addwebsocket(uid, gid);
            }
            window.location.href = '/index/'  //假设后端传回url
            window.location.reload()
        });

        // 根据提供的参数，生成一个li标签
        function generateli(time, msg, uid, attr) {
            if (attr == "left") {
                var div1 = document.createElement('div');
                div1.classList.add('message-content', 'p-3');
                div1.textContent = msg;

                var div2 = document.createElement('div');
                div2.classList.add('message-row', 'd-flex', 'align-items-center');
                div2.appendChild(div1);

                var span1 = document.createElement('span');
                span1.classList.add('class="date-time', 'text-muted');
                span1.textContent = uid + ',' + time;

                var div3 = document.createElement('div');
                div3.classList.add('message-body');
                div3.appendChild(span1);
                div3.appendChild(div2);

                var img1 = document.createElement('img');
                img1.classList.add('avatar', 'sm', 'rounded-circle');
                img1.src = "/static/images/user3.jpg";

                var div4 = document.createElement('div');
                div4.classList.add('mr-lg-3', 'me-2');
                div4.appendChild(img1);

                var li1 = document.createElement('li');
                li1.classList.add('d-flex', 'message');
                li1.appendChild(div4);
                li1.appendChild(div3);

                document.getElementById('chatbox').appendChild(li1);
            } else {
                var div1 = document.createElement('div');
                div1.classList.add('message-content', 'border', 'p-3');
                div1.textContent = msg;

                var div2 = document.createElement('div');
                div2.classList.add('message-row', 'd-flex', 'align-items-center', 'justify-content-end');
                div2.appendChild(div1);

                var span1 = document.createElement('span');
                span1.classList.add('date-time', 'text-muted');
                span1.textContent = uid + ',' + time;

                var div3 = document.createElement('div');
                div3.classList.add('message-body');
                div3.appendChild(span1);
                div3.appendChild(div2);

                var li1 = document.createElement('li');
                li1.classList.add('d-flex', 'message', 'right');
                li1.appendChild(div3);

                document.getElementById('chatbox').appendChild(li1);
            }
        }

        // 根据uid和gid 建立/获取 websocket连接
        function buildWebsocket(uid, gid) {
            if (wsdir[uid + gid] != null) { // 已经存在这个websocket了
                var socket = wsdir[uid + gid];
            } else {
                var arg = "ws://127.0.0.1:8888/ws/chat/" + gid + "/" + uid + "/";
                var socket = new WebSocket(arg);
                wsdir[uid + gid] = socket;
            }

            // 原本的逻辑是：
            //      我加入房间后还没点击房间，那么别的已经在房间聊天界面的用户，还是没法获取到最新的在线人数
            //      需要等我点击了房间后，别的用户才能更新在线人数

            // 现在修改逻辑
            // 加入房间后，发条消息给后端，这样聊天室的人数就可以更新了，而不需要当我点击了房间后再更新
            socket.onopen = function (event) {
                // console.log('连接')
                socket.send("enter");
            }

            socket.onmessage = function (event) {
                console.log(event);
                var data = JSON.parse(event.data);
                var attr = "";
                var gid = $('#sendmsg').attr('gid');

                // 点击群聊，获取消息时触发的
                if ('c_message' in data) {
                    // 在群聊聊天界面，才执行----更新在线人数
                    if ($('.main').css('display') !== 'none') {
                        if (data.c_message.gid == gid) {
                            console.log('点击群聊了，更新消息，当前用户id：', uid);
                            $('#online-user').find('span').text(data.c_message.gid_count);
                        }
                    }
                }

                // 有用户退出群聊了，触发
                if ('cq_message' in data) {
                    // 在群聊聊天界面，才执行----更新在线人数、显示退出的人是谁
                    if ($('.main').css('display') !== 'none') {
                        if (data.cq_message.gid == gid) {
                            console.log('用户退出群聊，当前用户id：', uid);
                            $('#online-user').find('span').text(data.cq_message.gid_count);
                            // 提示用户退出了
                            showAlert(data.cq_message.uid + '退出群聊', 3000); // 3秒后消失
                        }
                    }
                }

                // 聊天框内发消息----对话
                if ('message' in data) {
                    if (data.message.gid == gid) {
                        if (data.message.uid == uid) {
                            attr = "right";
                        } else {
                            attr = "left";
                        }
                        console.log("进来了");
                        generateli(data.message.time, data.message.text, data.message.uid, attr);
                    }
                }
            }
            return socket;
        }

        function addwebsocket(uid, gid) {
            $.ajax({
                url: "/add/websocket/",
                type: "get",
                data: { uid: uid, gid: gid },
                dataType: "JSON",
                success: function (request) {
                }
            });
        }

        // 点击发送消息按钮, 触发sendMessage事件
        function sendMessage() {
            var bt = $('#sendmsg');
            var socket = wsdir[bt.attr('uid') + bt.attr('gid')];
            let tag = document.getElementById("inputtxt");
            if (tag.value === '') {
                alert("请输入内容！");
            } else {
                socket.send(tag.value);
                var str = tag.value;
                tag.value = "";
                // 下面的ajax把消息添加到Message表中
                $.ajax({
                    url: "/storage/msg/",
                    type: "get",
                    data: { msg: str, gid: bt.attr('gid') },
                    dataType: "JSON",
                    success: function (request) {
                    }
                })
            }
        }

        // 点击退出按钮, closeConn
        function closeConn() {
            var bt = $('#sendmsg');
            var uid = bt.attr('uid');
            var gid = bt.attr('gid');
            var socket = wsdir[uid + gid];

            deletewesocket(uid, gid);
            // 通过消息来执行关闭连接的动作
            socket.send("close");

            // 重新加载
            window.location.href = '/index/'
            window.location.reload()
        }

        // 删除连接
        function deletewesocket(uid, gid) {
            $.ajax({
                url: "/delete/websocket/",
                type: "get",
                data: { uid: uid, gid: gid },
                dataType: "JSON",
                success: function (request) {
                }
            });
        }

        // 当该房间号的选项卡被选中触发事件
        function selectchat(self) {
            var gid = $(self).attr('gid'); // 获取点击事件的房号
            $('#roomid').text(gid); // 更新展示的聊天界面的房间房号
            $('#sendmsg').attr('gid', gid); // 为“发送消息”按钮设置gid属性

            // 点击群聊时，更新在线人数
            var socket = wsdir[$('#sendmsg').attr('uid') + $('#sendmsg').attr('gid')];
            socket.send('count');

            $.ajax({
                url: "/get/msg/",
                type: "get",
                data: { gid: gid },
                dataType: "JSON",
                success: function (request) {
                    // 把前端发过来的数据，添加到chatbox中
                    // 清屏
                    let ulElement = document.getElementById('chatbox'); // 替换 'yourUlId' 为你的 ul 元素的实际 ID
                    ulElement.innerHTML = ''; // 将 ul 元素的内容设置为空字符串
                    if (request.status) {
                        var objs = JSON.parse(request.queryset);
                        var uid = $('#sendmsg').attr('uid');
                        for (let i = 0; i < objs.length; i++) {
                            if (objs[i].fields.uid === uid) {
                                generateli(objs[i].fields.time, objs[i].fields.msg, objs[i].fields.uid, "right");
                            } else {
                                generateli(objs[i].fields.time, objs[i].fields.msg, objs[i].fields.uid, "left");
                            }
                        }
                    }
                }
            })
            $('.main').css('display', '');
        }

        // 提示框
        function showAlert(message, timeout = 3000) {
            const alertDiv = document.getElementById('alert');
            alertDiv.innerText = message;
            alertDiv.style.display = 'block';
            setTimeout(() => {
                alertDiv.style.display = 'none';
            }, timeout);
        }

        // 退出登录
        function leave() {
            // 如果退出登录
            location.href = "/log/";
        }

    </script>
</body>

</html>